import { fileURLToPath, URL } from 'node:url'
import type { ProxyOptions } from 'vite'
import { defineConfig, loadEnv } from 'vite'

import vue from '@vitejs/plugin-vue'
import DefineOptions from 'unplugin-vue-define-options/vite'

const envDir = './env'
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const ENV = loadEnv(mode, envDir)
  const prefix = process.env.VITE_DYNAMIC_PREFIX || ENV.VITE_BASE_PATH
  const proxyConf: Record<string, string | ProxyOptions> = {}
  proxyConf['/api'] = {
    // target: 'http://111.4.141.154:18080',
    target: 'http://10.4.1.132:8080',
    changeOrigin: true,
    rewrite: (path) => path.replace(ENV.VITE_BASE_PATH, '/')
  }
  proxyConf['/doc'] = {
    target: 'http://10.4.1.132:8080',
    changeOrigin: true,
    rewrite: (path) => path.replace(ENV.VITE_BASE_PATH, '/')
  }
  proxyConf['/static'] = {
    target: 'http://10.4.1.132:8080',
    changeOrigin: true,
    rewrite: (path) => path.replace(ENV.VITE_BASE_PATH, '/')
  }
  return {
    preflight: false,
    lintOnSave: false,
    base: prefix,
    envDir: envDir,
    plugins: [vue(), DefineOptions()],
    server: {
      cors: true,
      host: '0.0.0.0',
      port: Number(ENV.VITE_APP_PORT),
      strictPort: true,
      proxy: proxyConf
    },
    build: {
      target: "es2015",
      cssTarget: "chrome80",
      outDir: 'dist/ui',
      reportCompressedSize: false,
      // chunkSizeWarningLimit: 1200,
      // 生产环境移除console
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      },
      sourcemap: false,
      rollupOptions: {
        // external:[], // 外部依赖，不想打包进库的依赖
        output: {
          chunkFileNames: "js/[name]-[hash].js",
          entryFileNames: "js/[name]-[hash].js",
          assetFileNames: "[ext]/[name]-[hash].[ext]",
          manualChunks: {
            "lodash": ["lodash"],
            "logicflow": ["@logicflow/core", "@logicflow/extension"],
            "codemirror": ["codemirror", "@codemirror/theme-one-dark", "vue-codemirror"],
            "echarts": ["echarts"],
            "element-plus": ["element-plus", "use-element-plus-theme"],
            // "moment": ["moment"],
            "md-editor-v3": ["md-editor-v3"],
            "pinyin-pro": ["pinyin-pro"]
          }
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    }
  }
})
